package com.ywb.ex07;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 服务端口
 * @Author ywb
 */
public class Task3 extends Thread {
    String weather = "节目预报：八点有大型晚会，请收听";
//    端口号
    int port = 9998;
    InetAddress iaddress = null;
    MulticastSocket socket = null;

    Task3() {
        try {
//            指定多播地址实例化InetAddress,多播地址必须是244.0.0.1否则报错
            iaddress = InetAddress.getByName("224.0.0.1");
            socket = new MulticastSocket(port);
            // 指定发送范围是本地网络
            socket.setTimeToLive(1);
            // 加入广播组
            socket.joinGroup(iaddress);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() { // run()方法
        while (true) {
            // 声明DatagramPacket对象
            DatagramPacket packet;
            // 声明字节数组
            byte data[] = weather.getBytes();
            // 将数据打包
            packet = new DatagramPacket(data, data.length, iaddress, port);
            // 将广播信息输出
            System.out.println(new String(data));
            try {
                // 发送数据
                socket.send(packet);
                // 线程休眠
                sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new Task3().start();
    }
}
